package com.github.phoenics.militia.common.auth.session;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.phoenics.militia.common.exception.BaseResult;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import javax.servlet.ServletException;
import java.io.IOException;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static com.github.phoenics.militia.common.exception.BaseResult.fail;

/**
 * rest SessionInformationExpiredStrategy
 *
 * @author Phoenics Chow
 * on 2018年12月15日
 */
public class RestSessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {
    private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(RestSessionInformationExpiredStrategy.class);

    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent sessionInformationExpiredEvent) throws IOException, ServletException {
        String message="token is expired!";
        byte[] body = new ObjectMapper().writeValueAsBytes(BaseResult.fail(50014,message));
        sessionInformationExpiredEvent.getResponse().setContentType(APPLICATION_JSON_VALUE);
        sessionInformationExpiredEvent.getResponse().getOutputStream().write(body);
    }
}
